package com.ld.poetry.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ld.poetry.entity.ResourceConfig;
import com.ld.poetry.service.FileUploadService;
import com.ld.poetry.utils.CommonConst;
import com.ld.poetry.utils.FileUploadUtils;
import com.ld.poetry.vo.upload.FileSizeUnitEnums;
import com.ld.poetry.vo.upload.QiniuUploadInfo;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service(CommonConst.UPLOAD_TYPE_KEY_QINIU)
public class FileUploadQiniuServiceImpl implements FileUploadService {
    @Override
    public String upload(MultipartFile file, ResourceConfig config, String key) throws Exception {
        // 七牛配置信息
        QiniuUploadInfo qiniuUploadInfo = JSON.parseObject(config.getInfo(), QiniuUploadInfo.class);

        // 文件检验
        Long maxSizeLong = FileSizeUnitEnums.getMaxSizeLong(qiniuUploadInfo.getUnit(), qiniuUploadInfo.getMaxSize());
        FileUploadUtils.assertAllowed(file,maxSizeLong);

        //构建上传对象
        Configuration cfg = new Configuration(Region.region0());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        UploadManager uploadManager = new UploadManager(cfg);

        // 生成上传凭证，然后准备上传
        String accessKey = qiniuUploadInfo.getAccessKey();
        String secretKey = qiniuUploadInfo.getSecretKey();
        String bucket = qiniuUploadInfo.getBucket();

        // 构建上传的token
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        // 上传获取结果
        Response response = uploadManager.put(file.getBytes(), key, upToken);
        DefaultPutRet defaultPutRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);

        return config.getDownloadUrl() + "/" + defaultPutRet.key;
    }
}
